import axios from 'axios';
import { message } from 'ant-design-vue';
import { Local, Session } from '@/utils/storage';
import { getToken, getCookies } from '@/utils/auth'
import locale from "@/utils/i18n";

window.axiosCancel = []  // 全局定义一个存放取消请求的标识
const service = axios.create({
	baseURL: '/prod-api',
	timeout: 50000,
	headers: { 'Content-Type': 'application/json;charset=utf-8' },
});
const optionss: any = [
	{ value: 0, label: "47测试", url: 'prod-api', },
	{ value: 1, label: "Vincent本地", url: 'vincent-api', },
	{ value: 2, label: "Levi本地", url: 'Levi', },
	{ value: 3, label: "garrick本地", url: 'garrick', },
];
const basePath: any = import.meta.env.VITE_DEV_PREFIX;
// 添加请求拦截器
service.interceptors.request.use(
	(config) => {
		// 在发送请求之前做些什么 token
		if (Session.get(getToken())) {
			(<any>config.headers).common[getToken()] = `${Session.get(getToken())}`;
		}
		let configs = Local.get("envValue") ?? 0
		window.config.baseUrl = optionss.filter((l: any) => l.value === configs)[0]?.url;
		if (window.config.baseUrl) {
			config.baseURL = '/' + window.config.baseUrl;
		}
		// 添加取消标记
		config.cancelToken = new axios.CancelToken(cancel => {
			window.axiosCancel.push(cancel)
		})

		return config;
	},
	(error) => {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
);

// 添加响应拦截器
service.interceptors.response.use(
	(response: any) => {
		const urlList = ['/itf/organization/web/business_unit/export', '/itf/organization/web/enterprise/export']
		// 对响应数据做点什么
		const res = response.data;
		if (res.code && res.code !== 200) {
			// `token` 过期或者账号已在别处登录
			if (res.code === 401 || res.code === "401") {
				Session.clear(); // 清除浏览器全部临时缓存
				message.warning(locale.global.t("过期或者账号已在别处登录,重新登陆"));
				setTimeout(() => {
					// ${basePath}
					window.location.href = `/login`; // 去登录页
				}, 1500);
			} else {
				message.error(locale.global.t(res.code));
				return Promise.reject(response.data)
			}
			return response.data;
			// return Promise.reject(service.interceptors.response);
		} else if (urlList.includes(response.config.url)) {
			return { data: response.data, headers: response.headers }
		} else {
			return response.data;
		}
	},
	(error) => {
		console.log('error:', error);

		// 对响应错误做点什么
		if (error) {
			const code = error.response;
			if (code) {
				const { status } = code;
				const codeArr = [400, 401, 403, 404, 502, 500];
				if (codeArr.includes(status)) {
					message.error(locale.global.t(status));
				}
			} else {
				message.error(locale.global.t("网络错误"));
			}
		}
		return Promise.reject(error);
	}
);

// 导出 axios 实例
export default service;